package com.qfedu.edu.iotserver.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.qfedu.edu.exception.handler.BusinessException;
import com.qfedu.edu.pojo.Device;
import com.qfedu.edu.iotserver.mapper.DeviceMapper;
import com.qfedu.edu.iotserver.service.DeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qfedu.edu.result.ResponseCode;
import com.qfedu.edu.service.IJwtService;
import com.qfedu.edu.service.impl.JwtService;
import com.qfedu.edu.utils.DeviceKeyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * <p>
 * 设备表 服务实现类
 * </p>
 *
 * @author xiaobobo
 * @since 2024-09-13
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements DeviceService {

    @Autowired
    private IJwtService jwtService;

    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 添加设备
     * @param device
     * @param req
     */

    @Override
    public void add(Device device, HttpServletRequest req) {
        //校验参数
        if (null == device || StringUtils.isEmpty(device.getDeviceTypeId()) || StringUtils.isEmpty(device.getName())
                || StringUtils.isEmpty(device.getGroupId()) || StringUtils.isEmpty(device.getParentId())
                || StringUtils.isEmpty(device.getProductId()) || null == device.getDeviceIndex()){

            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION.getCode(),
                    ResponseCode.SMS_SEND_EXCEPTION.getMsg());
        }
        log.info("参数校验成功");

        synchronized (this) {//防止uuid在同一时间生成多个相同的key
            //参数无误
            //生成设备key
            device.setDeviceKey(DeviceKeyUtils.getDeviceKey());

            //设置设备的秘钥
            device.setDeviceSecret(UUID.randomUUID().toString().replace("-", "").trim());
        }

        //设置租户id
        String token = req.getHeader("token");
        String userId = jwtService.getUserId(token);
        device.setTenantId(userId);

        //设置是否激活 1：未激活 2：已激活
        device.setActive(1);

        //上传数据到数据库
        deviceMapper.insert(device);
        log.info("设备添加成功");

    }
}
